package com.lwl.multisource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class AppMainStarter extends WebMvcConfigurerAdapter {
	
	private static Logger LOG = LoggerFactory.getLogger(AppMainStarter.class);
	
	public static void main(String[] args) {
		LOG.info("App to Start ...");
		SpringApplication.run(AppMainStarter.class, args);
		
	}
	
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new HandlerInterceptor(){

			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
				String tenantId = request.getParameter("tenantId");
				LOG.info("tenantId=" + tenantId);
				
				if( StringUtils.isNotEmpty(tenantId) ) {
					TenantThreadLocal.setId(tenantId);
				}
				
				return true;
			}

			@Override
			public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { }
			@Override
			public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
				
			}}).addPathPatterns("/**");
		
		super.addInterceptors(registry);
	}
}
